package 高效制胜._11;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/9/18 16:46
 * 单词搜索
 * 算法：回溯
 * 注意字符不能重复使用
 * 遍历 board 数组，以当前元素为起点开始查找字符
 */
public class _79 {
    public static void main(String[] args) {
        char[][] board = new char[][]{{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
//        char[][] board = new char[][]{{'A', 'B', 'C'}, {'S', 'F', 'C'}};
        System.out.println(new _79().exist(board, "ABCCED"));
    }

    public boolean exist(char[][] board, String word) {
        int m = board.length, n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++)
                if (dfs(board, visited, i, j, word, 0)) return true;
        }
        return false;
    }

    public boolean dfs(char[][] board, boolean[][] visited, int i, int j, String s, int k) {
        if (board[i][j] != s.charAt(k)) return false;
        else if (k == s.length() - 1) return true;
        visited[i][j] = true;
        int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        boolean res = false;
        for (int[] dir : directions) {
            int newI = i + dir[0], newJ = j + dir[1];
            if (newI >= 0 && newI < board.length && newJ >= 0 && newJ < board[0].length) {
                if (!visited[newI][newJ]) {
                    boolean flag = dfs(board, visited, newI, newJ, s, k + 1);
                    if (flag) {
                        res = true;
                        break;
                    }
                }
            }
        }
        visited[i][j] = false;
        return res;
    }

}
